/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/platform/CodeUtils.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: CodeUtils.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (周一, 02 七月 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.codec;

import com.elancom.framework.commons.util.StringUtils;

/**
 * @author elancom
 * @date 2012-5-14
 */
public abstract class CodeBuilder {
	private static final String START = "1"; // 0
	private static final int DEFAULT_PART_LEN = 3;

	public static String build(String startCode) {
		return build(startCode, DEFAULT_PART_LEN);
	}

	public static String build(String startCode, int partLen) {
		if (partLen < 1) {
			throw new RuntimeException("段长不能小于1,不能生成新的编码");
		}

		if (StringUtils.isNotBlank(startCode)) {
			if (!StringUtils.isNumberString(startCode)) {
				throw new RuntimeException("当前只支持生成十进制的编码");
			}
			if (startCode.length() % partLen != 0) {
				throw new RuntimeException("开始编码长度并不是" + partLen + "的长度,不能生成新的编码");
			}
		} else {
			if (partLen == 0) {
				return START;
			}

			return StringUtils.join("0", "", partLen - 1) + START;
		}

		if (startCode.length() < partLen) {
			throw new RuntimeException("开始编码小雨");
		}

		final String c = startCode.substring(startCode.length() - partLen, startCode.length());
		// 溢出检查
		String lastPartCode = null;
		if (startCode.length() == partLen) { // 开始编码为第一级
			lastPartCode = startCode;
		} else {
			// 获取最后一级编码
			lastPartCode = startCode.substring(startCode.length() - partLen - 1, startCode.length());
		}

		if (lastPartCode.replaceAll("9", "").trim().length() == 0) {
			throw new RuntimeException("编码溢出");
		}

		final String prefix = startCode.substring(0, startCode.length() - partLen);
		String newCode = (Integer.valueOf(1 + c) + 1) + "";
		newCode = prefix + (newCode.toString().substring(1, partLen + 1));

		return newCode;
	}
}
